package com.example.secondhandspringboot.controller;


import com.example.secondhandspringboot.configuration.RabbitmqConfig;
import com.example.secondhandspringboot.constant.MessageConstant;
import com.example.secondhandspringboot.context.BaseContext;
import com.example.secondhandspringboot.domain.entity.UserBehavior;
import com.example.secondhandspringboot.exception.UserException;
import com.example.secondhandspringboot.results.Result;
import com.example.secondhandspringboot.service.IUserBehaviorService;
import com.example.secondhandspringboot.utils.IpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 用户行为表 前端控制器
 * </p>
 *
 * @author 周在林
 * @since 2024-05-28
 */
@RestController
@RequestMapping("/userBehavior")
@CrossOrigin
@Slf4j
@RequiredArgsConstructor
public class UserBehaviorController {

    private final IUserBehaviorService userBehaviorService;
    private final RabbitTemplate rabbitTemplate;

    @PostMapping("/saveBehavior")
    public Result saveBehavior(@RequestBody UserBehavior userBehavior, HttpServletRequest request){
        log.info("保存用户行为"+userBehavior);

        Long currentId = BaseContext.getCurrentId();
        if (currentId == null){
            throw new UserException(MessageConstant.USER_NOT_LOGIN);
        }
        userBehavior.setUserId(currentId);

        //设置sessionId
        userBehavior.setSessionId(request.getSession().getId());
        userBehavior.setIpAddress(request.getRemoteAddr());

        // TODO
//        userBehavior.setLocation(IpUtil.ipReverse(userBehavior.getIpAddress())==null?
//                "未知":IpUtil.ipReverse(userBehavior.getIpAddress()));
        userBehavior.setLocation(IpUtil.ipReverse("202.38.81.129")==null?"未知":IpUtil.ipReverse("202.38.81.129"));

        Integer behaviorType = userBehavior.getBehaviorType();
        if (behaviorType == 0){
            // 浏览 TODO
        } else if (behaviorType == 1) {
            // 搜索 TODO
        } else if (behaviorType == 2) {
            // 评论 TODO
        } else if (behaviorType == 3) {
            // 与商家联系 TODO
        }
        //将消息发往消息队列
        //为什么不绑定队列，因为交换机+routingkey 就等于匹配队列
        rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_NAME,RabbitmqConfig.ROUTING_KEY,userBehavior);
        log.info("rabbitmq消息发送成功");
        return Result.success();
    }
}
